/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package IO.models;

import Player.Player;
import Player.Rogue;
import Player.Warrior;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/**
 *
 * @author insane
 */
public class PlayerConfig {

    private static ArrayList<Player> player = null;
    private static PlayerConfig instance;

    public static PlayerConfig getInstance() throws FileNotFoundException, IOException, ClassNotFoundException {
        if (instance == null) {
            instance = new PlayerConfig();
        }
        return instance;
    }

    private PlayerConfig() throws FileNotFoundException, IOException, ClassNotFoundException {
        load();
    }

    public ArrayList<Player> getPlayers() {
        return this.player;
    }

    public Player getPlayer(String name) {
        for (int i = 0; i < player.size(); i++) {
            if (player.get(i).getName().equals(name)) {
                return player.get(i);
            }
        }
        return null;
    }

    public void save() throws FileNotFoundException, IOException {
        FileOutputStream fos = new FileOutputStream("players");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(player);
        oos.flush();
        oos.close();
    }

    public void load() throws FileNotFoundException, IOException, ClassNotFoundException {
        File f = new File("players");
        if (f.exists()) {
            FileInputStream fis = new FileInputStream("players");
            ObjectInputStream oin = new ObjectInputStream(fis);
            player = (ArrayList) oin.readObject();
        } else {
            player = new ArrayList<Player>();
            player.add(Warrior.getInstance());
            player.add(Rogue.getInstance());
            save();
        }
    }
}
